//index.js
//获取应用实例
import {
  getCoupon
} from '../../api/coupon.js'
const app = getApp()
Page({
  data: {
    coupons: [],
    busid: 0,
    currentType: 0,
    hasNoCoupons: true,
    little: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
    ids: '',
    loadingMoreHidden: false,
    isFinish: false,
    index: 1,
    statusType: [{
      name: '待使用',
      value: 'NEW'
    }, {
      name: '已使用',
      value: 'USED'
    }, {
      name: '已过期',
      value: 'EXPIRE'
    }],
  },
  onShow() {
    if (!wx.getStorageSync('access_token')) {
      wx.showModal({
        title: '请先登录',
        content: '',
        showCancel: false,
        success: (res) => {
          wx.navigateBack({
            delta: 1 //返回上一级页面
          })
        }
      })
      return
    }
    this.getCoupons()
  },
  statusTap(e) {
    if (e && e.hasOwnProperty("currentTarget")) {
      this.setData({
        currentType: e.currentTarget.dataset.index
      })
    } else {
      this.setData({
        currentType: e
      });
    }
    this.setData({
      coupons: [],
      isFinish: false,
      index: 1,
    })
    this.getCoupons()
    // this.onShow()
  },
  listenerCouponsInput: function (e) {
    this.data.coupons = e.detail.value;
    this.data.id = e.currentTarget.dataset.id;
  },
  listenerDuiHuan: function () {
    wx.request({
      url: app.globalData.urls + '/discounts/fetch',
      data: {
        // id: this.data.busid,
        pwd: this.data.coupons,
        token: app.globalData.token
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == 0) {
          wx.showToast({
            title: '礼券兑换成功',
            icon: 'success',
            duration: 2000
          })
        }
        if (res.data.code == 20001 || res.data.code == 20002) {
          wx.showModal({
            title: '兑换失败',
            content: '礼券已经兑换完了',
            showCancel: false
          })
          return;
        }
        if (res.data.code == 20003) {
          wx.showModal({
            title: '兑换失败',
            content: '兑换数量已达最大上限',
            showCancel: false
          })
          return;
        }
        if (res.data.code == 20000) {
          wx.showModal({
            title: '兑换失败',
            content: '输入的口令有误，请重新输入',
            showCancel: false
          })
          return;
        }
      }
    })
  },
  async onLoad(e) {
    var that = this
    if (app.globalData.iphone == true) {
      that.setData({
        iphone: 'iphone'
      })
    }
    if (e.ids) {
      this.setData({
        ids: e.ids
      })
    }
    wx.hideShareMenu()
  },
  showDesc(e) {
    wx.showModal({
      content: e.currentTarget.dataset.desc,
      showCancel: false
    })
  },

  select(e) {
    console.log(e.currentTarget.dataset.item);
    var item = e.currentTarget.dataset.item;
    if (item.IsUsed == 1) {
      return;
    }
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    prevPage.setData({
      coupon: item,
      allGoodsAndYunPrice: (prevPage.data.allGoodsAndYunPrice - item.price).toFixed(2)
    });
    wx.navigateBack({
      item
    });
  },
  goPay() {
    setTimeout(function () {
      wx.switchTab({
        url: '/pages/cloudPay/cloudPay',
        complete: res => {
          console.log(res)
        }
      })
    }, 200)
  },
  async getCoupons(ids) {
    var that = this
    if (this.data.isFinish) {
      return
    }
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    let status = that.data.statusType[that.data.currentType].value
    let res = await getCoupon(status, that.data.index, wx.getStorageSync('access_token'))
    console.log(res)
    wx.hideLoading()
    if (res && res.code == 10000) {
      if (res.data.records.length < 1) {
        that.setData({
          isFinish: true
        })
        if( that.data.index == 1 ){
          that.setData({
            loadingMoreHidden: false
          })
        }
        return
      } else {
        if (this.data.ids) {
          res.data.records.map(item => {
            if (item.scopeType == 'ALL') {
              item.beforeStatus = true
            } else if (console.log(item.scopeId.indexOf(this.data.ids)) > -1) {
              item.beforeStatus = true
            } else {
              item.beforeStatus = false
            }
          })
        }
        this.setData({
          coupons: res.data.records,
          index: that.data.index + 1,
          loadingMoreHidden: true
        })
        if( that.data.coupons.length < 1 ){
          that.setData({
            loadingMoreHidden: false
          })
        }
      }
    } else {
      that.setData({
        isFinish: true
      })
      return
    }
    // let url = 'coupon/get_coupons?CustId=' + app.globalData.uid
    // if (ids) {
    //   url = 'coupon/get_coupons?CustId=' + app.globalData.uid + '&GoodsIds=' + ids;
    // }

    // console.log()
    // app.get(url, res => {
    //   if (res && res.code == "0") {
    //     console.log(res.result);
    //     that.setData({
    //       // hasNoCoupons: false,
    //       coupons: res.result.map(item => {
    //         item.isExpried = (Date.parse(item.EndTime)) < (new Date()).getTime()
    //         item.EndTime = item.EndTime.substring(5, 10).replace("-", ".")
    //         item.CreateTime = item.CreateTime.substring(5, 10).replace("-", ".")
    //         item.Val = item.Val.substring(0, item.Val.indexOf("."))
    //         return item;
    //       })
    //     });
    //   }
    // });
  },
  goDrawCoupon() {
    this.setData({
      coupons: [],
      isFinish: false,
      index: 1,
    })
    wx.navigateTo({
      url: './drawCoupon',
    })
  },
})